package dao.impl;

import dao.CommodityDao;
import entity.Commodity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import utils.DruidUtils;
import java.util.List;

public class CommodityDaoImpl implements CommodityDao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
    @Override
    public List<Commodity> selectAllCommodities() {
        String sql = "select* from commodity";
        List<Commodity> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Commodity.class));
        return query;
    }

    @Override
    public List<Commodity> getCommodityByType(String type) {
        String sql = "select * from commodity where type=?";
        List<Commodity> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Commodity.class),type);
        return query;
    }

    @Override
    public void insertCommodity(Commodity commodity) {
        String sql = " insert into commodity (Cid, Wid, Cname,Type, Minimum, Quantity, " +
                "purchasing_price, sales_price, Size, Suid)" +
                "values (?,?,?,?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql,commodity.getCid(),commodity.getWid(),commodity.getCname(),
                                commodity.getType(),commodity.getMinimum(),commodity.getQuantity(),
                                commodity.getPurchasingPrice(),commodity.getSalesPrice(),
                                commodity.getSize(),commodity.getSuid());

    }

    @Override
    public Commodity getCommodityById(int id) {
        String sql = "select* from commodity where Cid = ?";
        Commodity query = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Commodity.class), id);
        return query;
    }

    @Override
    public List<String> getAllTypes() {
        String sql = "select distinct type from commodity";
        List<String> query = jdbcTemplate.queryForList(sql,String.class);
        return query;
    }

    @Override
    public void deleteCommodityById(int id) {
        String sql = "delete from commodity where Cid = ?";
        jdbcTemplate.update(sql,id);
    }
}
